package util

import (
	"fmt"
	"gopkg.in/yaml.v3"
	"io/ioutil"
	"log"
	"strings"
)

// ConfigMap 用于存储解析后的配置项
var ConfigMap map[string]interface{}

// 初始化配置
func init() {
	ConfigMap = make(map[string]interface{})
	if err := loadConfig("configs/application.yaml"); err != nil {
		log.Fatalf("Failed to load configuration: %v", err)
	}
}

// loadConfig 读取并解析 YAML 配置文件
func loadConfig(filePath string) error {
	// 读取文件内容
	data, err := ioutil.ReadFile(filePath)
	if err != nil {
		return err
	}

	// 解析 YAML 内容到 ConfigMap
	if err := yaml.Unmarshal(data, &ConfigMap); err != nil {
		return err
	}

	return nil
}

// GetNestedConfigValue 根据层级键获取配置值
func GetNestedConfigValue(keys []string, data map[string]interface{}) (interface{}, bool) {
	if len(keys) == 0 {
		return nil, false
	}

	key := keys[0]
	value, exists := data[key]
	if !exists {
		return nil, false
	}

	if len(keys) == 1 {
		return value, true
	}

	// 递归查找嵌套值
	nextMap, ok := value.(map[string]interface{})
	if !ok {
		return nil, false
	}

	return GetNestedConfigValue(keys[1:], nextMap)
}

// GetConfigValue 根据层级键（如 "some.nested.key"）获取配置值
func GetConfigValue(key string) (interface{}, error) {
	keys := strings.Split(key, ".")
	value, found := GetNestedConfigValue(keys, ConfigMap)
	if !found {
		return nil, fmt.Errorf("key %s not found in configuration", key)
	}
	return value, nil
}
